# == Schema Information
# Schema version: 6
#
# Table name: users
#
#  id              :integer(11)     not null, primary key
#  name            :string(255)     default(""), not null
#  email           :string(255)     default(""), not null
#  salt            :string(255)     
#  hashed_password :string(255)     default(""), not null
#  created_at      :datetime        
#

require 'digest/sha1'

class User < ActiveRecord::Base
  
  # valications
  validates_presence_of :name, :email, :password
  validates_uniqueness_of :name, :email
  
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, 
    :on => :create,
    :message=>"email format not valid..."
                    
  attr_accessor :password_confirmation 
  validates_confirmation_of :password
  
  # relations
  has_one :blog
  
  # 'password' is a virtual attribute
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def self.authenticate(name, password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  private
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt # 'wibble' makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
end
